package com.lagou.controller;

import com.lagou.dao.AuthCodeDao;
import com.lagou.pojo.AuthCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/code")
public class CodeController {
    @Autowired
    private AuthCodeDao authCodeDao;

    @RequestMapping("/create/{email}")
    public boolean create(@PathVariable String email){
        AuthCode authCode = new AuthCode();
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        authCode.setCode(code+"");
        authCode.setEmail(email);
        Date now = new Date();
        authCode.setCreatetime(now);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,10);
        authCode.setExpiretime(calendar.getTime());
        authCodeDao.save(authCode);
        return true;
    }

    @RequestMapping("/validate/{email}/{code}")
    public Integer validate(@PathVariable String email,@PathVariable String code){
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        Example<AuthCode> example = Example.of(authCode);
        Sort sort = new Sort(Sort.Direction.DESC,"expiretime");
        List<AuthCode> authCodeList = authCodeDao.findAll(example, sort);
        if (CollectionUtils.isEmpty(authCodeList)){
            return 1;
        }
        AuthCode authCode1 = authCodeList.get(0);
        if (authCode1.getExpiretime().before(new Date())){
            return 2;
        }
        return 0;
    }
}
